/**
 * 装备状态管理模块
 * 管理装备数据和装备操作
 */

import * as equipmentApi from '@/api/equipment'

const state = {
  // 玩家装备列表
  equipmentList: [],
  
  // 已装备的物品（仅四个槽位）
  equippedItems: {
    weapon: null,      // 武器
    helmet: null,      // 头盔
    armor: null,       // 护甲（衣服）
    boots: null        // 靴子
  },
  
  // 装备属性加成
  equipmentBonus: {
    constitution: 0,
    strength: 0,
    agility: 0,
    health: 0,
    defense: 0,
    speed: 0,
    baseDamage: 0,
    damageIncrease: 0,
    damageReduction: 0,
    critRate: 0,
    abnormalResist: 0,
    controlSuccess: 0,
    dodgeRate: 0,
    hitRate: 0
  },
  
  // 装备筛选条件
  filters: {
    type: 'all',      // 装备类型筛选
    quality: 'all',   // 品质筛选
    equipped: 'all'   // 装备状态筛选
  },
  
  // 加载状态
  loading: false,
  error: null
}

// 限制允许的槽位
const allowedSlots = ['weapon', 'helmet', 'armor', 'boots']

const mutations = {
  // 设置装备列表
  SET_EQUIPMENT_LIST(state, list) {
    state.equipmentList = list || []
  },
  
  // 设置已装备物品（过滤非法槽位）
  SET_EQUIPPED_ITEMS(state, items) {
    const next = { ...state.equippedItems }
    Object.keys(items || {}).forEach(slot => {
      if (allowedSlots.includes(slot)) {
        next[slot] = items[slot]
      }
    })
    state.equippedItems = next
  },
  
  // 设置装备属性加成
  SET_EQUIPMENT_BONUS(state, bonus) {
    state.equipmentBonus = { ...state.equipmentBonus, ...bonus }
  },
  
  // 装备物品（仅四槽位）
  EQUIP_ITEM(state, { item, slot }) {
    if (!allowedSlots.includes(slot)) return
    const equipment = state.equipmentList.find(eq => eq.id === item.id)
    if (equipment) {
      equipment.isEquipped = true
      equipment.slot = slot
    }
    state.equippedItems[slot] = item
  },
  
  // 卸下装备（仅四槽位）
  UNEQUIP_ITEM(state, slot) {
    if (!allowedSlots.includes(slot)) return
    const equippedItem = state.equippedItems[slot]
    if (equippedItem) {
      const equipment = state.equipmentList.find(eq => eq.id === equippedItem.id)
      if (equipment) {
        equipment.isEquipped = false
        equipment.slot = ''
      }
      state.equippedItems[slot] = null
    }
  },
  
  // 更新装备强化等级
  UPDATE_EQUIPMENT_LEVEL(state, { equipmentId, level, attributes }) {
    const equipment = state.equipmentList.find(eq => eq.id === equipmentId)
    if (equipment) {
      equipment.level = level
      equipment.currentAttributes = attributes
    }
    Object.keys(state.equippedItems).forEach(slot => {
      const item = state.equippedItems[slot]
      if (item && item.id === equipmentId) {
        item.level = level
        item.currentAttributes = attributes
      }
    })
  },
  
  // 设置筛选条件
  SET_FILTERS(state, filters) {
    state.filters = { ...state.filters, ...filters }
  },
  
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  // 设置错误信息
  SET_ERROR(state, error) {
    state.error = error
  },
  
  // 清除错误信息
  CLEAR_ERROR(state) {
    state.error = null
  }
}

const actions = {
  /**
   * 加载玩家装备列表
   * @param {Object} params - 请求参数
   * @param {number} params.type - 装备类型: 1=武器, 2=衣服, 3=头盔, 4=鞋子 (可选，0或未传则不过滤)
   * @param {boolean} params.is_select_up - 是否只获取可装备的装备（过滤已装备和等级超过玩家等级的）(可选)
   */
  async loadEquipmentList({ commit }, params = {}) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      // 构建请求参数，确保字段名与后端一致
      const requestParams = {}
      if (params.type !== undefined && params.type !== null) {
        requestParams.type = params.type
      }
      if (params.is_select_up !== undefined && params.is_select_up !== null) {
        requestParams.is_select_up = params.is_select_up
      }
      
      const response = await equipmentApi.getPlayerEquipments(requestParams)
      
      if (response.code === 200 || response.code === 1) {
        commit('SET_EQUIPMENT_LIST', response.data || [])
      } else {
        commit('SET_ERROR', response.msg || response.message || '加载装备列表失败')
      }
    } catch (error) {
      commit('SET_ERROR', error.message || '网络错误')
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 加载已装备物品（已废弃：装备数据从属性接口返回）
   * @deprecated 请使用 attribute store 中的装备数据
   */
  async loadEquippedItems({ commit }) {
    // 已废弃：装备数据现在从属性接口返回
    console.warn('loadEquippedItems 已废弃，装备数据应从属性接口获取')
  },
  
  /**
   * 装备物品
   * @param {Object} param0 - Vuex context
   * @param {Object} payload - { equipmentId: string|number } - 装备ID（可以是字符串或数字，会被转换为整数）
   * @note 后端不需要 slot 参数，会根据装备类型自动放到对应槽位
   */
  async equipItem({ commit, dispatch }, { equipmentId }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      // 将 equipmentId 转换为整数（后端需要 int 类型）
      const equipmentIdInt = parseInt(equipmentId, 10)
      if (isNaN(equipmentIdInt)) {
        commit('SET_ERROR', '装备ID无效')
        return { success: false, message: '装备ID无效' }
      }
      
      // 后端只需要 equipment_id，不需要 slot
      const response = await equipmentApi.equipItem({ equipment_id: equipmentIdInt })
      
      if (response.code === 200 || response.code === 1) {
        // 已废弃：装备数据现在从属性接口返回，不再需要单独调用
        await dispatch('loadEquipmentBonus')
        return { success: true, message: response.msg || '装备成功', code: response.code }
      } else {
        commit('SET_ERROR', response.msg || response.message || '装备失败')
        return { success: false, message: response.msg || response.message || '装备失败', code: response.code }
      }
    } catch (error) {
      const errorMsg = error.message || '网络错误'
      commit('SET_ERROR', errorMsg)
      return { success: false, message: errorMsg }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 卸下装备
   */
  async unequipItem({ commit, dispatch }, slot) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await equipmentApi.unequipItem({ slot })
      
      if (response.code === 200) {
        // 重新加载装备数据（已废弃 loadEquippedItems，装备数据从属性接口返回）
        await Promise.all([
          dispatch('loadEquipmentList'),
          dispatch('loadEquipmentBonus')
        ])
        
        // 通知属性模块更新装备加成
        await dispatch('attribute/updateEquipmentBonus', response.data.equipmentBonus, { root: true })
        
        return { success: true, message: '卸下装备成功' }
      } else {
        commit('SET_ERROR', response.message || '卸下装备失败')
        return { success: false, message: response.message || '卸下装备失败' }
      }
    } catch (error) {
      const errorMsg = error.message || '网络错误'
      commit('SET_ERROR', errorMsg)
      return { success: false, message: errorMsg }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 强化装备
   */
  async strengthenEquipment({ commit, dispatch }, { equipmentId, materialIds }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await equipmentApi.strengthenEquipment({
        equipment_id: equipmentId,
        material_ids: materialIds
      })
      
      if (response.code === 200) {
        // 更新装备信息
        commit('UPDATE_EQUIPMENT_LEVEL', {
          equipmentId,
          level: response.data.level,
          attributes: response.data.attributes
        })
        
        // 重新加载装备加成
        await dispatch('loadEquipmentBonus')
        
        // 通知属性模块更新装备加成
        await dispatch('attribute/updateEquipmentBonus', response.data.equipmentBonus, { root: true })
        
        return { success: true, message: '强化成功', data: response.data }
      } else {
        commit('SET_ERROR', response.message || '强化失败')
        return { success: false, message: response.message || '强化失败' }
      }
    } catch (error) {
      const errorMsg = error.message || '网络错误'
      commit('SET_ERROR', errorMsg)
      return { success: false, message: errorMsg }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 洗练装备（重塑部分进阶属性）
   */
  async washEquipment({ commit, dispatch }, { equipmentId }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await equipmentApi.washEquipment({
        equipment_id: equipmentId
      })
      
      if (response.code === 200) {
        // 更新装备信息（仅属性变化）
        commit('UPDATE_EQUIPMENT_LEVEL', {
          equipmentId,
          level: response.data.level || undefined,
          attributes: response.data.attributes || {}
        })
        
        // 重新加载装备加成
        await dispatch('loadEquipmentBonus')
        // 通知属性模块更新装备加成
        await dispatch('attribute/updateEquipmentBonus', response.data.equipmentBonus, { root: true })
        
        return { success: true, message: '洗练成功', data: response.data }
      } else {
        commit('SET_ERROR', response.message || '洗练失败')
        return { success: false, message: response.message || '洗练失败' }
      }
    } catch (error) {
      const errorMsg = error.message || '网络错误'
      commit('SET_ERROR', errorMsg)
      return { success: false, message: errorMsg }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 改造装备（调整部分基础属性加成）
   */
  async remodelEquipment({ commit, dispatch }, { equipmentId, focus }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await equipmentApi.remodelEquipment({
        equipment_id: equipmentId,
        focus
      })
      
      if (response.code === 200) {
        // 更新装备信息（基础属性变化）
        commit('UPDATE_EQUIPMENT_LEVEL', {
          equipmentId,
          level: response.data.level || undefined,
          attributes: response.data.attributes || {}
        })
        
        // 重新加载装备加成
        await dispatch('loadEquipmentBonus')
        // 通知属性模块更新装备加成
        await dispatch('attribute/updateEquipmentBonus', response.data.equipmentBonus, { root: true })
        
        return { success: true, message: '改造成功', data: response.data }
      } else {
        commit('SET_ERROR', response.message || '改造失败')
        return { success: false, message: response.message || '改造失败' }
      }
    } catch (error) {
      const errorMsg = error.message || '网络错误'
      commit('SET_ERROR', errorMsg)
      return { success: false, message: errorMsg }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 加载装备属性加成
   */
  async loadEquipmentBonus({ commit }) {
    try {
      const response = await equipmentApi.getEquipmentBonus()
      
      if (response.code === 200) {
        commit('SET_EQUIPMENT_BONUS', response.data || {})
        return response.data
      }
    } catch (error) {
      console.error('加载装备属性加成失败:', error)
    }
    return {}
  },
  
  /**
   * 设置筛选条件
   */
  setFilters({ commit }, filters) {
    commit('SET_FILTERS', filters)
  },
  
  /**
   * 清除错误信息
   */
  clearError({ commit }) {
    commit('CLEAR_ERROR')
  }
}

const getters = {
  // 筛选后的装备列表
  filteredEquipmentList: (state) => {
    let filtered = state.equipmentList
    
    // 按类型筛选
    if (state.filters.type !== 'all') {
      filtered = filtered.filter(item => item.type === state.filters.type)
    }
    
    // 按品质筛选
    if (state.filters.quality !== 'all') {
      filtered = filtered.filter(item => item.quality === state.filters.quality)
    }
    
    // 按装备状态筛选
    if (state.filters.equipped === 'equipped') {
      filtered = filtered.filter(item => item.isEquipped)
    } else if (state.filters.equipped === 'unequipped') {
      filtered = filtered.filter(item => !item.isEquipped)
    }
    
    return filtered
  },
  
  // 已装备物品数量
  equippedCount: (state) => {
    return Object.values(state.equippedItems).filter(item => item !== null).length
  },
  
  // 装备槽位是否已满
  isSlotEquipped: (state) => (slot) => {
    if (!allowedSlots.includes(slot)) return false
    return state.equippedItems[slot] !== null
  },
  
  // 获取指定槽位的装备
  getEquippedItem: (state) => (slot) => {
    if (!allowedSlots.includes(slot)) return null
    return state.equippedItems[slot]
  },
  
  // 总装备属性加成
  totalEquipmentBonus: (state) => {
    return state.equipmentBonus
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}